package cn.exrick.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.exrick.mapper.TbPreferentialItemMapper;
import cn.exrick.pojo.TbPreferentialItem;
import cn.exrick.service.PreferentialItemService;
import cn.exrick.utils.mybatis.Criteria;

@Service
public class PreferentialItemServiceImpl extends BaseServiceImpl<TbPreferentialItem, TbPreferentialItemMapper> implements PreferentialItemService {
    private final static Logger log = LoggerFactory.getLogger(PreferentialItemServiceImpl.class);

    @Override
    public Logger getLogger() {
        return log;
    }

    public Criteria createCriteria(Map<String, Object> params) {
        Criteria criteria = createCriteria();
        if (params.get("preferentialId") != null) {
            criteria.andFieldEqualTo("preferential_id", String.valueOf((Long) params.get("preferentialId")));
        }
        if (params.get("itemId") != null) {
            criteria.andFieldEqualTo("item_id", String.valueOf((Long) params.get("itemId")));
        }
        if (params.get("status") != null) {
            criteria.andFieldEqualTo("status", String.valueOf((Integer) params.get("status")));
        }
        return criteria;
    }

    @Autowired
    TbPreferentialItemMapper tbPreferentialItemMapper;

    @Override
    public TbPreferentialItemMapper getMapper() {
        return tbPreferentialItemMapper;
    }

    @Override
    public boolean exist(long preferentialId, long itemId) {
        return findByPreferentialIdAndItemId(preferentialId, itemId,null) != null;
    }

    @Override
    public List<TbPreferentialItem> findByItemId(long itemId, Integer status) {
        Criteria criteria = createCriteria(new HashMap<String, Object>() {{
            this.put("itemId", itemId);
            if(status != null){
                this.put("status", status);
            }
        }});
        return findListByCriteria(criteria);
    }

    @Override
    public TbPreferentialItem findByPreferentialIdAndItemId(long preferentialId, long itemId, Integer status) {
        Criteria criteria = createCriteria(new HashMap<String, Object>() {{
            this.put("preferentialId", preferentialId);
            this.put("itemId", itemId);
            if(status != null){
                this.put("status", status);
            }
        }});
        List<TbPreferentialItem> list = findListByCriteria(criteria);
        if (list == null || list.size() <= 0) {
            return null;
        } else {
            return list.get(0);
        }
    }
}
